package com.admin.core;

import com.admin.utils.RedisUtilKey;
import com.tiangong.framework.BusinessBus;
import com.tiangong.framework.bo.AbstractSign;
import com.tiangong.framework.bo.CDO;
import com.tiangong.framework.bo.Return;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.*;
import java.util.stream.Collectors;

@Component
@Slf4j
public class Sign extends AbstractSign {

    /**
     * Sign签名校验认证
     * 签名规则：MD5(token +&参数1+&参数2 +&参数3 +&参数4  )(参数按照首字母排序，32位小写加密md5)
     * @param cdoRequest - 业务参数
     * @param request    - token签名
     * @return
     * @author
     * @create: 2023年10月23日18:43:37
     */
    @Override
    public boolean isValid(HttpServletRequest request, CDO cdoRequest) {
        //获取token
        String token = request.getHeader("token");
        String sign = request.getHeader("sign");
        //获取访问路径
        String servletPath = request.getServletPath();
        if (substring(servletPath)) {
            return true;
        }
        if (this.servletPath(servletPath)) {
            if (token == null || sign == null) {
                return false;
            }
            if (tokenState(token)) {//token是否有效
                return tokenSign(cdoRequest,sign,token);
            } else {
                return false;
            }
        } else {
            return true;
        }
    }

    //设置权限路径
    public boolean servletPath(String servletPath) {
        CDO path = new CDO();
        path.set("/rest/v2/userLogin/sys_login", true);
        //path.set("/rest/v1/voteUserTokenService/getVoteUserTokenPage", true);
        if (path.containsKey(servletPath)) {
            return false;
        } else {
            return true;
        }
    }

    //截取指定字段
    public boolean substring(String servletPath) {
        if ("v1".equals(servletPath.substring(6, 8))) {
            return true;
        }
        return false;
    }

    //token 校验
    public boolean tokenState(String token) {
        //获取当前token数据
        CDO cdoResult = CDO.newRequest("voteUserTokenService", "getVoteUserTokenPage");
        cdoResult.set("token_value", token);
        //cdoResult.set("token_state",cdoRequest.getString("token_state"));
        Return voteUserToke = BusinessBus.handleService(cdoResult);
        if (voteUserToke.getData().containsKey("token_state")){
            if (voteUserToke.getData().getInteger("token_state") == 0) {//token是否有效
                //获取参数值map
                Timestamp effectiveTime = voteUserToke.getData().getTimestamp("effective_time");
                long currentTimeMillis = System.currentTimeMillis();
                if (effectiveTime.getTime()<currentTimeMillis){
                    return false;
                }
                return true;
            } else {
                return false;
            }
        }else {
            return false;
        }
    }

    //Sign校验
    public boolean tokenSign(CDO cdoRequest,String sign,String token ) {

        //获取参数值map
        Map<String, Object> keymap = cdoRequest.getInnerMap();
        //获取map的key set集合
        Set<String> keySet = keymap.keySet();
        //按首字母排序排序
        List<String> keySetOrder = keySet.stream().sorted(Comparator.naturalOrder()).collect(Collectors.toList());
        //循环参数值
        for (int i = 0; i < keySetOrder.size(); i++) {
            String keyValue = keymap.get(keySetOrder.get(i)).toString().trim();
            token += "&" + keyValue.trim();
            log.info("检查sign" + token);
        }
        //32位小写加密
        String md5Util = DigestUtils.md5Hex(token);
        if (sign.equals(md5Util)) {
            return true;
        } else {
            return false;
        }
    }


    public static void main(String[] args) {
        System.out.println();
        String rest = "/rest/v1/userLogin/sys_login" ;
        System.out.println(rest);
    }
}
